package hfdp.chp05;

/**
 * If performance is an issue in your use of the getInstance() method then this method of implementing the Singleton can
 * drastically reduce the overhead.
 * Created by chei on 2016/3/31.
 */
public class SingletonWithDoubleChkLock {

    /**
     * The volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized
     * to the Singleton instance.
     */

    private volatile static SingletonWithDoubleChkLock uniqueInstance;

    private SingletonWithDoubleChkLock(){

    }

    public static SingletonWithDoubleChkLock getInstance() {
        // Check for an instance and if there isn’t one, enter a synchronized block.
        if(null == uniqueInstance){
            // Note we only synchronize the first time through!
            synchronized (SingletonWithDoubleChkLock.class) {
                if(null == uniqueInstance) {
                    // Once in the block, check again and if still null, create an instance.
                    uniqueInstance = new SingletonWithDoubleChkLock();
                }
            }
        }
        return uniqueInstance;
    }
}
